import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/controller/schooladmin.dart';
import 'package:ichinesereader/models/common/userStatusDto.dart';
import 'package:ichinesereader/models/school/teacherItem.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/dialogs/resetTeacherEmail.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import 'package:intl/intl.dart';
import 'package:toggle_switch/toggle_switch.dart';
import '../../pages/schooladmin/adminTeacherEditor.dart';
import 'package:ichinesereader/themes/appTheme.dart';
import '../../themes/pageStyles.dart';
import '../dialogs/resetTeacherPassword.dart';
import 'package:ichinesereader/themes/buttonStyles.dart';

// ignore: must_be_immutable
class TeacherDataGrids extends StatelessWidget {
  TeacherDataGrids(this.isWebOrDesktop, this.teacherItems);

  List<TeacherItem> teacherItems;
  bool isWebOrDesktop = GetPlatform.isMacOS || GetPlatform.isWeb;
  List<DataGridRow> dataGridRows = <DataGridRow>[];

  DataGridController _dataGridController = DataGridController();
  SchoolAdminController _schoolAdminController = Get.find();
  AppButtonStyles _appButtonStyles = new AppButtonStyles();
  final PageStyles _pageStyles = PageStyles();

  @override
  Widget build(BuildContext context) {
    Log.debug('build TeacherDataGrids');
    return Column(children: [
      Container(
        padding: EdgeInsets.all(12.0),
        decoration: BoxDecoration(
          color: Get.isDarkMode
              ? AppTheme.colors.darkTheme2
              : Colors.white.withOpacity(0.3),
          borderRadius: BorderRadius.circular(3.0),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            ElevatedButton(
                style: _appButtonStyles.createButtonStyle(),
                child: Text(
                  'Create'.tr,
                  style: TextStyle(
                      color: Get.isDarkMode ? Colors.black : Colors.white),
                ),
                onPressed: () {
                  _schoolAdminController
                      .fetchSchoolAllClassesDetailsWithoutAll();
                  Get.to(() => AdminTeacherEditor());
                }),
            SizedBox(width: 12),
            ElevatedButton(
                style: _appButtonStyles.removeButtonStyle(),
                child: Text(
                  'Delete'.tr,
                  style: TextStyle(
                      color: Get.isDarkMode ? Colors.black : Colors.white),
                ),
                onPressed: () {
                  if (this._dataGridController.selectedRows.length > 0) {
                    this._dataGridController.selectedRows.forEach((row) {
                      var cid = row
                          .getCells()
                          .where((element) => element.columnName == 'Id')
                          .first
                          .value;
                      var item = teacherItems
                          .where((element) => element.objectId == cid)
                          .first;
                      _schoolAdminController
                          .removeTeacher(item.userName.toString())
                          .then((statusMesage) {
                        if (statusMesage.status == 1000) {
                          Get.snackbar('Message'.tr, 'Successfully removed'.tr,
                              backgroundColor: Theme.of(context).primaryColor,
                              colorText: Theme.of(context).primaryColorLight,
                              snackPosition: SnackPosition.BOTTOM);
                        } else {
                          Get.snackbar('Message'.tr, 'Please try again!'.tr,
                              backgroundColor: Theme.of(context).primaryColor,
                              colorText: Theme.of(context).primaryColorLight,
                              snackPosition: SnackPosition.BOTTOM);
                        }
                      });
                      // teacherItems
                      //     .removeWhere((element) => element.objectId == cid);
                    });
                  } else {
                    Get.snackbar('Message'.tr,
                        'Please choose at least one to delete!'.tr,
                        backgroundColor: Theme.of(context).primaryColor,
                        colorText: Theme.of(context).primaryColorLight,
                        snackPosition: SnackPosition.BOTTOM);
                  }
                }),
            SizedBox(width: 12),
            ElevatedButton(
                style: _appButtonStyles.disableButtonStyle(),
                child: Text(
                  'Reset Password'.tr,
                  style: TextStyle(
                      color: Get.isDarkMode ? Colors.black : Colors.white),
                ),
                onPressed: () {
                  if (this._dataGridController.selectedRows.length > 0) {
                    DataGridRow row =
                        this._dataGridController.selectedRows.first;
                    var cid = row
                        .getCells()
                        .where((element) => element.columnName == 'Id')
                        .first
                        .value;
                    var item = teacherItems
                        .where((element) => element.objectId == cid)
                        .first;
                    showGeneralDialog(
                        context: Get.context!,
                        transitionDuration: Duration(milliseconds: 400),
                        pageBuilder: (bc, ania, anis) {
                          return ResetTeacherPasswordDialog(
                              userName: item.userName ?? '');
                        });
                  } else {
                    Get.snackbar(
                        'Message'.tr, 'Please choose and try again!'.tr,
                        backgroundColor: Theme.of(context).primaryColor,
                        colorText: Theme.of(context).primaryColorLight,
                        snackPosition: SnackPosition.BOTTOM);
                  }
                }),
            SizedBox(width: 12),
            ElevatedButton(
                style: _appButtonStyles.exportButtonStyle(),
                child: Text(
                  'Change Email'.tr,
                  style: TextStyle(
                      color: Get.isDarkMode ? Colors.black : Colors.white),
                ),
                onPressed: () {
                  if (this._dataGridController.selectedRows.length > 0) {
                    DataGridRow row =
                        this._dataGridController.selectedRows.first;
                    var cid = row
                        .getCells()
                        .where((element) => element.columnName == 'Id')
                        .first
                        .value;
                    var item = teacherItems
                        .where((element) => element.objectId == cid)
                        .first;
                    showGeneralDialog(
                        context: Get.context!,
                        transitionDuration: Duration(milliseconds: 400),
                        pageBuilder: (bc, ania, anis) {
                          return ResetTeacherEmailDialog(
                              userName: item.userName ?? '');
                        });
                  } else {
                    Get.snackbar(
                        'Message'.tr, 'Please choose and try again!'.tr,
                        backgroundColor: Theme.of(context).primaryColor,
                        colorText: Theme.of(context).primaryColorLight,
                        snackPosition: SnackPosition.BOTTOM);
                  }
                })
          ],
        ),
      ),
      SizedBox(height: 12),
      Expanded(child: _buildDataGrid()),
    ]);
  }

  Container _buildDataGrid() {
    if (GetPlatform.isDesktop || GetPlatform.isWeb) isWebOrDesktop = true;

    return Container(
      decoration: _pageStyles.dataGridBackground(),
      child: Container(
        margin: EdgeInsets.all(12.0),
        decoration: _pageStyles.dataGridForground(),
        child: SfDataGrid(
          source: TeacherDataGridSource(items: teacherItems),
          isScrollbarAlwaysShown: true,
          onQueryRowHeight: (row) {
            return row.rowIndex == 0 ? 50.0 : 49.0;
          },
          //设置表头高度
          showCheckboxColumn: true,
          checkboxColumnSettings: Get.isDarkMode
              ? DataGridCheckboxColumnSettings(
                  backgroundColor: Color(0xff0a0e21),
                )
              : DataGridCheckboxColumnSettings(
                  backgroundColor: Colors.blue[50]),
          allowSorting: true,
          allowTriStateSorting: true,
          allowSwiping: true,
          allowFiltering: true,
          selectionMode: SelectionMode.multiple,
          navigationMode: GridNavigationMode.cell,
          controller: _dataGridController,
          endSwipeActionsBuilder:
              (BuildContext context, DataGridRow row, int rowIndex) {
            return GestureDetector(
                onTap: () {
                  var cid = row
                      .getCells()
                      .where((element) => element.columnName == 'Id')
                      .first
                      .value;

                  var item = teacherItems
                      .where((element) => element.objectId == cid)
                      .first;

                  _schoolAdminController
                      .removeTeacher(item.userName.toString());

                  Get.snackbar('Message'.tr, 'Successfully Removed'.tr,
                      backgroundColor: Theme.of(context).primaryColor,
                      colorText: Theme.of(context).primaryColorLight,
                      snackPosition: SnackPosition.BOTTOM);
                },
                child: Container(
                    color: Colors.redAccent,
                    child: Center(
                      child: Icon(Icons.delete),
                    )));
          },
          columns: <GridColumn>[
            GridColumn(
              width: isWebOrDesktop ? 160 : 120,
              columnName: 'FirstName',
              label: buildDataGridColumnLabel('FirstName'),
            ),
            GridColumn(
              columnName: 'LastName',
              width: isWebOrDesktop ? 160 : 120,
              label: buildDataGridColumnLabel('LastName'),
            ),
            GridColumn(
              columnName: 'UserName',
              width: isWebOrDesktop ? 220 : 180,
              label: buildDataGridColumnLabel('UserName'),
            ),
            GridColumn(
              columnName: 'Class',
              width: isWebOrDesktop ? 320 : 250,
              label: buildDataGridColumnLabel('Class'),
            ),
            GridColumn(
              columnName: 'Homework',
              allowFiltering: false,
              width: isWebOrDesktop ? 130 : 100,
              label: buildDataGridColumnLabel('Homework'),
            ),
            GridColumn(
              columnName: 'Enabled',
              allowFiltering: false,
              width: isWebOrDesktop ? 120 : 120,
              label: buildDataGridColumnLabel('Enabled?'),
            ),
            GridColumn(
              columnName: 'LastLogin',
              allowFiltering: false,
              width: isWebOrDesktop ? 170 : 120,
              label: buildDataGridColumnLabel('LastLogin'),
            ),
            GridColumn(
              columnName: 'Id',
              allowFiltering: false,
              width: 10,
              visible: false,
              label: buildDataGridColumnLabel('Id'),
            ),
          ],
        ),
      ),
    );
  }
}

class TeacherDataGridSource extends DataGridSource {
  TeacherDataGridSource({required List<TeacherItem> items}) {
    dataGridRows = items
        .map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
              DataGridCell<String>(
                  columnName: 'FirstName', value: dataGridRow.firstName),
              DataGridCell<String>(
                  columnName: 'LastName', value: dataGridRow.lastName),
              DataGridCell<String>(
                  columnName: 'UserName', value: dataGridRow.userName),
              DataGridCell<String>(
                  columnName: 'Class',
                  value: dataGridRow.className != null
                      ? json.encode(dataGridRow.className)
                      : null),
              DataGridCell<int>(
                  columnName: 'Homework', value: dataGridRow.totalAssignment),
              DataGridCell<bool>(
                  columnName: 'Enabled',
                  value: dataGridRow.disabled as bool ? false : true),
              DataGridCell<int>(
                  columnName: 'LastLogin', value: dataGridRow.lastLoggedIn),
              DataGridCell<String>(
                  columnName: 'Id', value: dataGridRow.objectId),
            ]))
        .toList();
  }

  List<DataGridRow> dataGridRows = [];
  SchoolAdminController _schoolAdminController = Get.find();

  @override
  List<DataGridRow> get rows => dataGridRows;

  @override
  DataGridRowAdapter? buildRow(DataGridRow row) {
    //列表隔行Row的颜色 // https://help.syncfusion.com/flutter/datagrid/conditional-styling
    Color setRowBackgroundColor() {
      final int index = effectiveRows.indexOf(row);
      if (index % 2 != 0) {
        return Get.isDarkMode ? Colors.black : Colors.grey[200]!;
      }
      return Colors.transparent;
    }

    return DataGridRowAdapter(
        color: setRowBackgroundColor(),
        cells: row.getCells().map<Widget>((dataGridCell) {
          if (dataGridCell.columnName == 'Class') {
            var tempstr = '';
            if (dataGridCell.value != null) {
              List<String> items =
                  List<String>.from(json.decode(dataGridCell.value.toString()));
              items.forEach((element) {
                tempstr = tempstr + element.toString() + ',';
              });
              tempstr = tempstr.substring(0, tempstr.length - 1);
            }
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: Text(
                  tempstr,
                  softWrap: true,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: Get.textTheme.bodySmall,
                ));
          } else if (dataGridCell.columnName == 'UserName') {
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: GestureDetector(
                    onTap: () {
                      String teacherId = row
                          .getCells()
                          .where((element) => element.columnName == 'Id')
                          .first
                          .value;
                      Get.to(() => AdminTeacherEditor(teacherId: teacherId));
                    },
                    child: Text(
                      dataGridCell.value.toString(),
                      style: Get.textTheme.titleLarge,
                      overflow: TextOverflow.ellipsis,
                    )));
          } else if (dataGridCell.columnName == 'LastLogin') {
            if (dataGridCell.value > 0) {
              return Container(
                  alignment: Alignment.center,
                  padding: EdgeInsets.symmetric(horizontal: 16.0),
                  child: Text(
                    DateFormat('MM/dd/yyyy kk:mm').format(
                        DateTime.fromMillisecondsSinceEpoch(
                            dataGridCell.value)),
                    overflow: TextOverflow.ellipsis,
                    style: Get.textTheme.bodySmall,
                  ));
            } else {
              return Container(
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.symmetric(horizontal: 16.0),
                  child: Text(
                    ' - ',
                    overflow: TextOverflow.ellipsis,
                    style: Get.textTheme.bodySmall,
                  ));
            }
          } else if (dataGridCell.columnName == 'Enabled') {
            return Container(
              alignment: Alignment.center,
              padding: EdgeInsets.symmetric(horizontal: 8.0),
              child: ToggleSwitch(
                customWidths: [55.0, 40.0],
                minHeight: 24,
                cornerRadius: 20.0,
                activeBgColors: Get.isDarkMode
                    ? [
                        [Get.theme.primaryColorDark],
                      ]
                    : [
                        [Get.theme.primaryColorDark],
                        [Get.theme.primaryColorDark]
                      ],
                activeFgColor:
                    Get.isDarkMode ? Colors.black : Get.theme.primaryColorLight,
                inactiveBgColor: Get.isDarkMode
                    ? Get.theme.primaryColor
                    : AppTheme.colors.darkTheme9,
                inactiveFgColor: Get.theme.primaryColorLight,
                totalSwitches: 2,
                initialLabelIndex: dataGridCell.value ? 0 : 1,
                labels: ['Yes', ''],
                icons: [null, Icons.disabled_by_default_rounded],
                onToggle: (index) {
                  var classname = row
                      .getCells()
                      .where((element) => element.columnName == 'Class')
                      .first
                      .value;
                  if (classname != null && classname != '') {
                    if (index == 1) {
                      Get.snackbar(
                          'Message'.tr,
                          'Cannot disable teacher account that has classes associated'
                              .tr,
                          backgroundColor: AppTheme.colors.primary,
                          colorText: AppTheme.colors.primaryLight,
                          snackPosition: SnackPosition.BOTTOM);
                    } else {
                      UserStatusDto dto = new UserStatusDto();
                      dto.enable = true;
                      dto.userNames = [];
                      var username = row
                          .getCells()
                          .where((element) => element.columnName == 'UserName')
                          .first
                          .value;
                      dto.userNames!.add(username);
                      _schoolAdminController.updateTeachersStatus(dto);
                    }
                  } else {
                    UserStatusDto dto = new UserStatusDto();
                    dto.enable = index == 0 ? true : false;
                    dto.userNames = [];
                    var username = row
                        .getCells()
                        .where((element) => element.columnName == 'UserName')
                        .first
                        .value;
                    dto.userNames!.add(username);
                    _schoolAdminController.updateTeachersStatus(dto);
                  }
                },
              ),
            );
          } else {
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: Text(
                  dataGridCell.value.toString(),
                  overflow: TextOverflow.fade,
                  style: Get.textTheme.bodySmall,
                ));
          }
        }).toList());
  }
}
